package com.atguigu.day07;

import com.atguigu.utils.OrderEvent;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.cep.CEP;
import org.apache.flink.cep.PatternFlatSelectFunction;
import org.apache.flink.cep.PatternFlatTimeoutFunction;
import org.apache.flink.cep.PatternStream;
import org.apache.flink.cep.pattern.Pattern;
import org.apache.flink.cep.pattern.conditions.SimpleCondition;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.List;
import java.util.Map;

// 超时订单检测
public class Example4 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<OrderEvent> stream = env
                .fromElements(
                        new OrderEvent("order-1", "create", 1000L),
                        new OrderEvent("order-2", "create", 2000L),
                        new OrderEvent("order-1", "pay", 4000L)
                )
                .assignTimestampsAndWatermarks(WatermarkStrategy.<OrderEvent>forMonotonousTimestamps()
                        .withTimestampAssigner(new SerializableTimestampAssigner<OrderEvent>() {
                            @Override
                            public long extractTimestamp(OrderEvent element, long recordTimestamp) {
                                return element.ts;
                            }
                        }));

        Pattern<OrderEvent, OrderEvent> pattern = Pattern
                .<OrderEvent>begin("create-order")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("create");
                    }
                })
                .next("pay-order")
                .where(new SimpleCondition<OrderEvent>() {
                    @Override
                    public boolean filter(OrderEvent value) throws Exception {
                        return value.type.equals("pay");
                    }
                })
                // 5秒之内匹配成功
                .within(Time.seconds(5));

        PatternStream<OrderEvent> patternStream = CEP.pattern(stream.keyBy(r -> r.orderId), pattern);

        SingleOutputStreamOperator<String> result = patternStream
                .flatSelect(
                        // 用来接收超时信息
                        new OutputTag<String>("timeout-info") {
                        },
                        new PatternFlatTimeoutFunction<OrderEvent, String>() {
                            @Override
                            public void timeout(Map<String, List<OrderEvent>> pattern, long timeoutTimestamp, Collector<String> out) throws Exception {
                                // 将超时信息发送到侧输出流
                                OrderEvent create = pattern.get("create-order").get(0);
                                out.collect("订单：" + create.orderId + "超时未支付。");
                            }
                        },
                        new PatternFlatSelectFunction<OrderEvent, String>() {
                            @Override
                            public void flatSelect(Map<String, List<OrderEvent>> pattern, Collector<String> out) throws Exception {
                                OrderEvent pay = pattern.get("pay-order").get(0);
                                out.collect("订单：" + pay.orderId + "支付成功。");
                            }
                        }
                );

        result.print();

        result.getSideOutput(new OutputTag<String>("timeout-info"){}).print();

        env.execute();
    }
}
